require "vector.lua"
require "dbg.lua"
require "simulation.lua"


 

--balance the setup, to be in the center of mass system
do 
  dofile"Setup1.lua"
  local mass = 0
  for _,m in ipairs(Masses) do
    mass = mass + m
  end

  --normalize the positions
  local center = 0*Positions[1]
  for i,pos in ipairs(Positions) do
    center = center + Masses[i]*pos
  end
  center = Vector{love.graphics.getWidth(), love.graphics.getHeight()}/2 - center / mass
  for i,pos in ipairs(Positions) do
    Positions[i] = pos + center
  end
  
  --normalize the speeds
  impulse = 0*Speeds[1]
  for i, spd in ipairs(Speeds) do
    impulse = impulse + Masses[i]*spd
  end
  impulse = impulse / mass
  for i, spd in ipairs(Speeds) do
    Speeds[i] = spd - impulse 
  end
end

trajectory = {}


state = Vector{Positions, Speeds}
-- simulation
-- decoupling actual simultaion and the display
-- we do the claculations in the simulation with a fixed interval
elapsed = 0
tick_size = 0.1
next_tick = tick_size
display_state = state
function love.update(dt)
  dt = dt * 10
  local display_delta = dt
  elapsed = elapsed + dt
  local start = love.timer.getTime()
  while next_tick< elapsed do
    state = advance(state, tick_size)
    display_state = state
    display_delta = elapsed - next_tick
    next_tick = next_tick + tick_size
    trajectory[#trajectory+1] = state[1]
	if (love.timer.getTime()-start>1) then 
		display_delta = 0
		break 
	end
  end
  display_state = advance_simple(display_state, display_delta)
end



function love.draw()
  
  --trajectories
  love.graphics.setColor(100,100,100)
  for step = 2, #trajectory do
    for i, cur in ipairs(trajectory[step]) do
      love.graphics.line(trajectory[step-1][i][1],trajectory[step-1][i][2],cur[1], cur[2])
    end
  end

  --positions
  for i, pos in ipairs(display_state[1]) do
    local color = Colors[i] or { 200,200,200 }
    local size = Sizes[i] or math.sqrt(math.sqrt(Masses[i]))
    love.graphics.setColor( unpack(color) )
    love.graphics.circle("fill", pos[1], pos[2], size, size)
  end
  dbg.add("min", minscale)
  dbg.add("max", maxscale)
  dbg.flush()
end
